package cn.xjt.Unsafe;

/**
 * 线程不安全案例
 * 不安全的买票
 * @author xujiangtao
 * @create 2020-08-01-13:04
 */
public class TestBuyticket {
    public static void main(String[] args) {
        ticket t = new ticket();
        new Thread(t,"苦逼的我").start();
        new Thread(t,"牛逼的你们").start();
        new Thread(t,"可恶的黄牛").start();
    }
}
class ticket implements Runnable{

    //票
    private int ticket = 10;
    boolean flag = true;
    //买票
    @Override
    public void run() {

        while (flag)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buy();
        }
    }
    public synchronized void buy()
    {
        if(ticket<=0)
        {
            flag=false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买了票"+ticket--);
    }
}
